package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.DAOUtil;
import model.dao.MessageDAO;
import model.entity.Message;
import servlets.util.ParamUtil;
import util.JSONUtil;
import exceptions.ParameterNotFoundException;

/**
 * Servlet implementation class ReceiveMessageServlet
 */
@WebServlet("/ReceiveMessageServlet")
public class ReceiveMessageServlet extends HttpServlet {

	private static final long serialVersionUID = -7251474301788002677L;

	public ReceiveMessageServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Parâmetros do protocolo
		List<String> paramNames = Arrays.asList("island_id", "user_id",
				"message_base_id", "direction", "limit");
		Map<String, String> params = new HashMap<String, String>();
		try {
			params = ParamUtil.getValues(request, paramNames);
		} catch (ParameterNotFoundException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		Long user_id;
		Long island_id;
		Long message_base_id;
		Boolean direction;
		Integer limit;
		try {
			user_id = Long.parseLong(params.get("user_id"));
			island_id = Long.parseLong(params.get("island_id"));
			message_base_id = Long.parseLong(params.get("message_base_id"));
			direction = Boolean.parseBoolean(params.get("direction"));
			limit = Integer.parseInt(params.get("limit"));
		} catch (NumberFormatException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		MessageDAO dao = new MessageDAO(Message.class);
		List<Message> messages = dao.findAllLimited(island_id, message_base_id, direction, limit);
		DAOUtil<Message> daoUtil = new DAOUtil<Message>();
		daoUtil.listDetached(messages);
		PrintWriter pw = response.getWriter();
		pw.write(JSONUtil.toJSON(messages));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

}
